<template>
  <div>
    <!-- 头部搜索 -->
    <el-card>
      <el-form :inline="true">
        <el-row>
          <el-col :span="21">
            <el-form-item label="角色名称">
              <el-input v-model="formParamse.username" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- table区域 -->
    <el-card style="margin: 10px 0;">
      <div style="margin-bottom: 10px;">
        <el-button type="primary" icon="Plus" @click="editRole('add',{})">添加角色</el-button>
      </div>
      <el-table :data="tableData" border style="width: 100%;margin-bottom: 10px;">
        <el-table-column align="center" prop="" label="#" type="index" width="80" />
        <el-table-column align="center" prop="id" label="id" width="80" />
        <el-table-column align="center" prop="roleName" label="角色名称" />
        <el-table-column align="center" prop="createTime" label="创建时间" />
        <el-table-column align="center" prop="updateTime" label="更新时间" />
        <el-table-column align="center" label="操作" width="280">
          <template #default="scope">
            <el-button type="primary" size="small" @click="changeDrawer(scope.row)">
              <el-icon>
                <User />
              </el-icon>
              分配权限
            </el-button>
            <el-button type="primary" size="small" @click="editRole('update',scope.row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-popconfirm :title="`确定删除`">
              <template #reference>
                <el-popconfirm :title="`确定删除${scope.row.roleName}?`" width="220px" @confirm="delRole(scope.row)">
                  <template #reference>
                    <el-button size="small" type="danger">
                      <el-icon>
                        <Delete />
                      </el-icon>
                      删除
                    </el-button>
                  </template>
                </el-popconfirm>

              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @current-change="getDataList" @size-change="sizeChange" v-model:current-page="currentPage"
        v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]" background
        layout="prev,pager,next,jumper,-> ,sizes,total" :total="total" />
    </el-card>
    <!-- 添加和编辑弹框 -->
    <el-dialog v-model="dialogVisible" :title="`${dialogForm.id != '' ? '编辑':'添加'}`" width="500">
      <div>
        <el-form>
          <el-form-item label="角色名称">
            <el-input v-model="dialogForm.roleName" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog">取消</el-button>
          <el-button type="primary" @click="confirmDialog">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配权限的抽屉 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <div>
          <el-tree ref="tree" style="max-width: 600px" :data="menuList" show-checkbox node-key="id" default-expand-all
            :default-expanded-keys="selectArr" :props="defaultProps" />
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelDrawer">取消</el-button>
          <el-button type="primary" @click="confirmDrawer">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref,reactive,onMounted } from 'vue';
import {reqAllRoleList,reqAddOrUpdateRole,reqAllMenuList,reqSetPermission,reqRemoveRole} from '@/api/acl/role/index'
import type {Records,RoleResponseData,RoleData} from '@/api/acl/role/type'
import { ElMessage } from 'element-plus'
let currentPage = ref<number>(1)
let pageSize = ref<number>(3)
let total = ref<number>(10)
//搜索条件
let formParamse = reactive({

  username:'',
})
//弹框信息
let dialogForm = reactive({
    id:'',
  roleName:'',
})
const tableData = ref<Records>([])
let dialogVisible = ref<boolean>(false)
let drawer = ref<boolean>(false)
let menuList = ref<any>([])
let selectArr = ref<any>([])
let tree = ref()
//获取列表数据接口
const getDataList = async()=>{
  let res:RoleResponseData = await reqAllRoleList(currentPage.value,pageSize.value,formParamse.username)
  if(res.code == 200){
    tableData.value = res.data.records
    total.value = res.data.total

  }
}
onMounted(()=>{
  getDataList()
})
// 点击每页条数
const sizeChange = ()=>{
  currentPage.value = 1
  getDataList()

}
//搜索
const search = ()=>{
   currentPage.value = 1
  getDataList()
}
//重置
const reset = ()=>{
    Object.assign(formParamse,{
      username:'',
    })
  currentPage.value = 1
  getDataList()
}

//点击或修改添加角色按钮
const editRole = (type:string,row:RoleData)=>{
  Object.assign(dialogForm,{
     id:'',
     roleName:'',
  })
  if(type == 'add'){

  }else{
    Object.assign(dialogForm,row)
  }
  dialogVisible.value = true
}
//点击取消弹框按钮
const cancelDialog = ()=>{
  dialogVisible.value = false
}
//点击确认弹框按钮
const confirmDialog = async()=>{
  let res = await reqAddOrUpdateRole(dialogForm)
  if(res.code == 200){
    ElMessage({
      type:'success',
      message:`${dialogForm.id != '' ? '编辑成功' : '新增成功'}`
    })
    if(dialogForm.id == '' || !dialogForm.id){
       currentPage.value = 1
    }
    getDataList()
    dialogVisible.value = false
  }else{
    ElMessage({
      type:'success',
      message:`${dialogForm.id != '' ? '编辑失败' : '新增失败'}`
    })
  }
  
}


//点击分配权限
const changeDrawer = async(row:RoleData)=>{
  
   Object.assign(dialogForm,row)
  let res:any = await reqAllMenuList(row.id as number)
  if(res.code == 200){
    drawer.value = true
    menuList.value = res.data.allPermissions
    //默认选中的
    selectArr.value = filterSelectArr(menuList.value,[])
  }

}
const defaultProps = {
  children: 'children',
  label: 'name',
}
//递归
const filterSelectArr = (allData:any,initArr:any)=>{
  if(!allData) return initArr
  allData.forEach((item:any)=>{
    //判断最后一级
    if(item.select && item.level === 4){
      initArr.push(item.id)
    }
    //判断是否有子节点
    if(item.children && item.children.length > 0){
      filterSelectArr(item.children,initArr)
    }
  })
  return initArr

}
//取消抽屉的事件
const cancelDrawer = ()=>{
  drawer.value = false
}
//确认抽屉的事件
const confirmDrawer = async()=>{
  const roleId:any = dialogForm.id 
  let arr = tree.value.getCheckedKeys()
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  let res:any = await reqSetPermission(roleId,permissionId)
  if(res.code == 200){
    drawer.value = false
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    })
    getDataList()
    // window.location.reload()
  }
  
}
// 删除事件
const delRole = async(row:RoleData)=>{
  let res:any = await reqRemoveRole(row.id as number)
  if(res.code == 200){
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    tableData.value.length > 1 ? currentPage.value : currentPage.value - 1
    getDataList()
  }else{
     ElMessage({
      type:'success',
      message:'删除失败'
    })
  }
}
</script>

<style scoped></style>
